package com.yx.changdao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yx.changdao.common.data.Result;
import com.yx.changdao.common.entity.*;
import com.yx.changdao.common.exception.AlertException;
import com.yx.changdao.common.mapper.CommunityBuildDetailMapper;
import com.yx.changdao.common.utils.ExcelImportExportUtils;
import com.yx.changdao.common.utils.Faster;
import com.yx.changdao.common.utils.IDCheck;
import com.yx.changdao.common.utils.SysUtils;
import com.yx.changdao.service.*;
import org.nutz.lang.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: <br/>
 * 户信息表
 * <p>
 * <br/>
 * @Auther: flexible
 * @create 2020/04/02 13:47
 */
@Service
public class CommunityBuildDetailServiceImpl extends ServiceImpl<CommunityBuildDetailMapper, CommunityBuildDetail> implements CommunityBuildDetailService {
    /**
     * 部门联户人小组服务
     */
    @Autowired
    private DepContactGroupService depContactGroupService;

    @Autowired
    private SysUserService sysUserService;
    /**
     * 社区建筑物表服务
     */
    @Autowired
    private CommunityBuildService communityBuildService;
    /**
     * 户的服务
     */
    @Autowired
    private CommunityBuildDetailService communityBuildDetailService;
    @Autowired
    private CommunityResidentService communityResidentService;

    /**
     * 根据建筑id查有那几户
     */
    @Override
    public List<CommunityBuildDetail> getBuidDetailByBuildId(Integer buildId) {
        return this.list(new QueryWrapper<CommunityBuildDetail>().lambda()
                .eq(CommunityBuildDetail::getBuildId, buildId)
                .orderByDesc(CommunityBuildDetail::getCreateTime));
    }
    /* */

    /**
     * 根据单元，室查出具体用户
     *//*
    @Override
    public CommunityBuildDetail getUserByUnit(Integer unit, String houseNumber) {
        return this.getOne(new QueryWrapper<CommunityBuildDetail>().lambda()
                .eq(CommunityBuildDetail::getUnit,unit)
                .eq(CommunityBuildDetail::getHouseNumber,houseNumber));
    }*/
    @Override
    public boolean removeResident(Integer id) {
        //居民id
        List<CommunityResident> residents = communityResidentService.list
                (new QueryWrapper<CommunityResident>().in(CommunityResident.BUILD_DETAIL_ID, id));
        for (CommunityResident integer : residents) {
            integer.setBuildDetailId(0);
            //更新居民
            communityResidentService.updateById(integer);
        }
        return true;
    }

    @Override
    public CommunityBuildDetail getOneByBuildIdAndUnit(String buildCode, String doorPlate, Integer unit) {
        CommunityBuild build =
                communityBuildService.getOne(new QueryWrapper<CommunityBuild>().eq(CommunityBuild.BUILD_CODE, buildCode));
        if (build == null) {
            return null;
        }
        CommunityBuildDetail communityBuildDetail = communityBuildDetailService.getOne(new QueryWrapper<CommunityBuildDetail>()
                .eq(CommunityBuildDetail.BUILD_ID, build.getId())
                .eq(CommunityBuildDetail.DOOR_PLATE, doorPlate)
                .eq(CommunityBuildDetail.UNIT, unit));
        return communityBuildDetail;
    }

    @Override
    public Map<String, Object> checkAndSave(MultipartFile communityBuildDetailFile) throws AlertException {
        //不合格的
        List<CommunityBuildDetail> failed = new ArrayList<>();
        List<CommunityBuildDetail> successNum = new ArrayList<>();
        List<CommunityBuildDetail> updateNum = new ArrayList<>();
        List<Integer> faildNum = new ArrayList<>();
        Integer[] num = {2};
        ExcelImportExportUtils.readExcel(CommunityBuildDetail.class, communityBuildDetailFile, (communityBuildDetail) -> {
            num[0] = num[0] + 1;
            try {
                if (Faster.isNull(communityBuildDetail)) {
                    throw new AlertException();
                }
                if (Strings.isBlank(communityBuildDetail.getBuildCode())) {
                    throw new AlertException("楼编号不能为空");
                }
                if (Strings.isNotBlank(communityBuildDetail.getIdCard())) {
                    if (communityBuildDetail.getIdCard().length() != 15 && communityBuildDetail.getIdCard().length() != 18) {
                        throw new AlertException("身份证不合法");
                    }
                }
                String[] split = communityBuildDetail.getBuildCode().split("-");
                communityBuildDetail.setBuildId(Integer.parseInt(split[1]));
                if (Strings.isBlank(communityBuildDetail.getDoorPlate())) {
                    throw new AlertException("室号不能为空");
                }
                if (Strings.isBlank(communityBuildDetail.getUserName())) {
                    throw new AlertException("户主姓名不能为空");
                }
                if (communityBuildDetail.getUnit() == null) {
                    throw new AlertException("单元不能为空");
                }
               /* if (Strings.isBlank(communityBuildDetail.getGroupName())) {
                    throw new AlertException("联户人小组不允许不填哟");
                }*/
                //获取当前登录用户id
                String userId = SysUtils.currentUserId();
                //用户信息
//                SysUser sysUser = sysUserService.getOne(new QueryWrapper<SysUser>().eq(SysUser.USER_ID, userId));
               /* DepContactGroup depContactGroup = depContactGroupService.
                        getOne(new QueryWrapper<DepContactGroup>()
                                .eq(DepContactGroup.GROUP_NAME, communityBuildDetail.getGroupName())
                                .eq(DepContactGroup.DEP_ID, sysUser.getDepId()));
                if (depContactGroup == null) {
                    throw new AlertException("该小组不存在");
                }
                communityBuildDetail.setGroupName(depContactGroup.getGroupName());
                communityBuildDetail.setContactGroupId(depContactGroup.getContactGroupId());*/
                DepContactGroup depContactGroup = depContactGroupService.getOne
                        (new QueryWrapper<DepContactGroup>().eq(DepContactGroup.CONTACT_GROUP_ID,
                                communityBuildDetail.getContactGroupId()));
                if(depContactGroup==null){
                    throw new AlertException("该小组不存在");
                }

                CommunityBuildDetail communityBuildDetail1 = communityBuildDetailService.getOne(new QueryWrapper<CommunityBuildDetail>()
                        .eq(CommunityBuildDetail.BUILD_ID, communityBuildDetail.getBuildId())
                        .eq(CommunityBuildDetail.DOOR_PLATE, communityBuildDetail.getDoorPlate())
                        .eq(CommunityBuildDetail.UNIT, communityBuildDetail.getUnit()));

                if (communityBuildDetail1 == null) {
                    save(communityBuildDetail);
                    successNum.add(communityBuildDetail);
                } else {
                    communityBuildDetail.setId(communityBuildDetail1.getId());
                    updateById(communityBuildDetail);
                    updateNum.add(communityBuildDetail);
                }

            } catch (Exception e) {
                faildNum.add(num[0]);
                failed.add(communityBuildDetail);
            }
        });
        Map<String, Object> map = new HashMap<>();
        map.put("saveNum", successNum.size());
        map.put("updateNum", updateNum.size());
        map.put("failedNum", failed.size());
        map.put("rows", faildNum);
        map.put("list", failed);
        return map;
    }

}
